package com.tsingtree.modular.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsingtree.base.pojo.page.LayuiPageFactory;
import com.tsingtree.base.pojo.page.LayuiPageInfo;
import com.tsingtree.modular.entity.NanSellerTag;
import com.tsingtree.modular.entity.NanUser;
import com.tsingtree.modular.entity.NanUserDevice;
import com.tsingtree.modular.mapper.NanUserMapper;
import com.tsingtree.modular.model.params.NanUserParam;
import com.tsingtree.modular.model.result.NanUserResult;
import com.tsingtree.modular.service.NanSellerTagService;
import com.tsingtree.modular.service.NanUserDeviceService;
import com.tsingtree.modular.service.NanUserService;
import com.tsingtree.roses.core.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author jagger
 * @since 2023-08-29
 */
@Service
public class NanUserServiceImpl extends ServiceImpl<NanUserMapper, NanUser> implements NanUserService {

    @Autowired
    private NanUserDeviceService nanUserDeviceService;
    @Autowired
    private NanSellerTagService nanSellerTagService;

    @Override
    public void add(NanUserParam param){
        NanUser entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(NanUserParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(NanUserParam param){
        NanUser oldEntity = getOldEntity(param);
        NanUser newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public NanUserResult findBySpec(NanUserParam param){
        return null;
    }

    @Override
    public List<NanUserResult> findListBySpec(NanUserParam param){
        return this.baseMapper.customPageList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(NanUserParam param){
        Page<NanUserResult> pageContext = getPageContext();
        IPage<NanUserResult> page = this.baseMapper.customPageList(pageContext, param);
        List<NanUserDevice> list = nanUserDeviceService.list(new QueryWrapper<NanUserDevice>().orderByAsc("id"));
        Map<Integer, NanUserDevice> map = new HashMap<>();
        list.forEach(device -> {
            if(!map.containsKey(device.getUserId())){
                map.put(device.getUserId(), device);
            }
        });
        Map<Integer, String> tagMap = nanSellerTagService.list().stream().collect(Collectors.toMap(NanSellerTag::getId, NanSellerTag::getName));
        page.getRecords().forEach((user) -> {
            NanUserDevice device = map.get(user.getId());
            if(Objects.nonNull(device)){
                user.setSellerId(device.getSellerId());
                user.setDeviceCode(device.getCode());
            }
            String tag = user.getTag();
            if(StringUtils.hasText(tag)){
                String[] tags = tag.split(",");
                StringBuilder names = new StringBuilder();
                for(String tagStr : tags){
                    int key = Integer.parseInt(tagStr.substring(1, tagStr.length() - 1));
                    String name = tagMap.get(key);
                    names.append(" | ").append(name);
                }
                user.setTagStr(names.substring(3));
            }
        });
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    @Transactional
    public void updateUser(NanUser nanUser) {
        if (!this.updateById(nanUser)) {
            throw new RuntimeException();
        }
    }

    private Serializable getKey(NanUserParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private NanUser getOldEntity(NanUserParam param) {
        return this.getById(getKey(param));
    }

    private NanUser getEntity(NanUserParam param) {
        NanUser entity = new NanUser();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
